jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;

            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
var getObj = function (id) {
	return "string" == typeof id ? document.getElementById(id) : id;
};

var isFirstToCart = true;//判断是否第一次点击加入购物车
var url=window.location.href;
var pid=$("#goodsid").val();
var pname=$(".info-right h1 .pname").html();

var pprice=$(".specials em strong").html();
var pimg=$("#imgUrl").val();
var purl="/view-"+pid+".html";




$('.attribute  ul li').click(function(){
	$(this).addClass('selected').siblings().removeClass('selected');
	var spec_name = $(this).parent().parent().prev().html();
	var type =  $(this).parent().parent().prev().attr('lab');
	var spec_value = $(this).find('a').html();
	var price  = 0;
	if(type == 'attr_volume'){ 
		var price = $(this).attr('price');
		$("#trueprice").html('￥'+price+'元');
	}
	$(this).parent().next().val(spec_name+":"+spec_value+"$"+price)
	//$value = $(this).find('a').html();
	//alert($(this).find('a').html());
});
/***************************************************************/




//图片展示切换 小图切换大图
function tabimg(btn,imgobj,cls,bsrc,ssrc){
	$(btn).mouseover(function(){
		$(this).siblings().removeClass('imgselect');
		//$(this).siblings().find('b').remove();
		$('#imgshow').find('b').remove();
		$(this).addClass(cls);
		$(this).prepend('<b></b>');
		$(imgobj).attr('src',$(this).attr(bsrc));
		$(imgobj).attr('alt',$(this).attr(ssrc));
	});
};

//放大镜
function imgQuan(){
	$("img.jqzoom").jqueryzoom({
		xzoom: 473,
		yzoom: $("div.proInfobox")[0].offsetHeight,
		offset: 44,
		position: "right",
		iTop:-34
	});
};

//分享按钮切换
function shareBtn(btn,x,y,l,hy){
	$(btn).each(function(i){
		$(this).css('background-position',i*-l-x+'px '+-y+'px');
		$(this).hover(function(){$(this).css('background-position',i*-l-x+'px '+-hy+'px');}
		,function(){$(this).css('background-position',i*-l-x+'px '+-y+'px');})
	});
};

//$('#info-share a').share($('h1 span').text(),'',$('.jqzoom').attr('src'));



//数量加减特效   会往上提
function sum(minbtn,maxbtn){
	minbtn.click(function(){						 
		var ht = $(this).next().find('input').val()*1;
		$(this).next().find('input').val(++ht);
		var nu=$("#quantity").val();
		$("#buynum").val(nu);
		return false;
	});
	maxbtn.click(function(){
		var ht = $(this).prev().find('input').val()*1;
		ht > 1 && $(this).prev().find('input').val(--ht);
		var nu=$("#quantity").val();
		$("#buynum").val(nu);
		return false;
	});
};
function changeSum(){
	$("#buynum").val($("#quantity").val());
}

//最近浏览展示
function history_show(){
	var history_info=$.cookie("history_info");
	var content="";	
	if(history_info!=null){
		history_arg=history_info.split("$");
		var i;
		for(i=0;i<5;i++){
	    	if(history_arg[i]!=null && history_arg[i]!="undefined"){
		    	var wlink=history_arg[i].split("+");
				if(wlink != null && wlink[2] != null && wlink[2] != ""){
					var imgsrc=wlink[0];					
					content+="<dl>";
					content+="<dt><a target='_blank' title='"+wlink[2]+"' href='"+wlink[1]+"'><img src='"+ imgsrc +"'/></a></dt>";
					content+="<dd class='nam'><a target='_blank' title='"+wlink[2]+"' href='"+wlink[1]+"'>"+wlink[2]+"</a></dd>";
					content+="</dl>";
				}
			}else{
                break;
            }
		}
		if(content!=""){
			$(".sidebar").append("<h3>最近浏览过的商品</h3><div>"+content+"</div>");
		}
	}
};

//最近浏览放入cookie
function glog(){  
	try{
		var linkname = pname+"$";
		var address = purl;
		var hisImg = pimg;
		var wlink= hisImg + "+" + address + "+"+linkname;
		var old_info=$.cookie("history_info");
		var insert=true;
		if(old_info==null){
			insert=true;
		}else{
			var old_link=old_info.split("$");
			for(var j=0;j<8;j++)
			{   
			    if(old_link[j] == null){break;}
				if(old_link[j].indexOf(pname)!=-1)
				{insert=false;
				break;}
			}
		}	
		if(insert){
			var oldcookie = $.cookie("history_info");
			var oldcoo = "";
			if(oldcookie != null){
				var oldlink = oldcookie.split("$");
				if(oldlink.length > 8){
					for(var j=0;j<7;j++){   
						oldcoo += oldlink[j]+"$";
					}
					wlink += oldcoo;
				}else{
					wlink += $.cookie("history_info");
				}
			}else{
				wlink += $.cookie("history_info");
			}
			$.cookie('history_info',wlink,{expires: 7, path: '/', domain: '', secure: false});
		}
	}catch(e){}
	return true;
};




	
//图片延迟加载
function loadImgInfo(o){
	var imgWarp = parseInt(o.id.replace(/\D/g,""));
	document.getElementById("cont"+imgWarp).innerHTML = document.getElementById("cont"+imgWarp).getElementsByTagName("textarea")[0].value;
}

function lazyload(option){
   var settings={defObj:null,defHeight:0};
   settings=jQuery.extend(settings,option||{});
   var defHeight=settings.defHeight,defObj=(typeof settings.defObj=="object")?settings.defObj.find("img"):jQuery(settings.defObj).find("img");
   var pageTop=function(){
   	 var d=document,y=(navigator.userAgent.toLowerCase().match(/iPad/i)=="ipad")?window.pageYOffset:Math.max(d.documentElement.scrollTop,d.body.scrollTop);
   	 return d.documentElement.clientHeight+y-settings.defHeight
   };
   var imgLoad=function(){
     defObj.each(
       function(){
         if(jQuery(this).offset().top<=pageTop()){
           var src2=jQuery(this).attr("src2");
           if(src2){
             jQuery(this).attr("src",src2).removeAttr("src2")
           }
         }
     })
 };
imgLoad();
jQuery(window).bind("scroll",function(){imgLoad()}
)}
lazyload({defObj:"#detail"});
////////////////////////////////////////////////////
tabimg('#imgshow dd a','#imgshow dt img','imgselect','bigsrc','supsrc');//小图切换大图
imgQuan();//放大镜
//shareBtn('#info-share a',159,116,22,99);//分享滑动变亮效果

if($('#selbtn').length > 0){
	copySelect($('#selbtn'),$('#sellist'),$('#colorId'));//多个sku
}
sum($('#min'),$('#max'));//数量增减
joinCart('.join','#alt-succ','.succ-close');//加入购物车
history_show();//最近浏览展示
glog();//最近浏览加入cookie






//统计代码
function cartwt(pid){
    
}

//加入购物车
function joinCart(btn,obj,clo){
	$(btn).click(function(){
			var attr_color = $("#attr_color").val();
			var attr_volume = $("#attr_volume").val();
			var buynum = $("#quantity").val();
			var units = $("#units").val();
			var carttip="该商品已成功放入购物车";
			var countmoney="购物车共 <b>0</b> 件商品     合计：<b>0</b> 元";
			$.post("/plus/posttocar.php?do=ajaxadd",{id:pid,attr_color:attr_color,attr_volume:attr_volume,buynum:buynum,units:units},function(result){
    			//$("span").html(result);
				result = $.parseJSON(result);
				if(!result.error){
					countmoney="购物车共 <b>"+result.buynum+"</b> 件商品     合计：<b>"+result.totalCount+"</b> 元";
                	$('#cartbuy').text($('#cartbuy').text(result.totalCount));
                	$("#alt-succ div p:first").html(countmoney);
                	$("#alt-succ div p:first").show();
                	$("#alt-succ div h3").html(carttip);
                  	$(obj).show();					
				}
  			});
		});
	$(clo).click(function(){
    	isFirstToCart = true;
		$(this).parent().hide();
		return false;
	});
};
//购物车继续购物链接
function close_cart(){
	isFirstToCart = true;
	$(".alt-succ").hide();
}
//获取url中的参数
function request(paras){ 
	var url = location.href;  
	var paraString = url.substring(url.indexOf("?")+1,url.length).split("&");  
	var paraObj = {}  
	for (i=0; j=paraString[i]; i++){  
		paraObj[j.substring(0,j.indexOf("=")).toLowerCase()] = j.substring(j.indexOf("=")+1,j.length);  
	}  
	var returnValue = paraObj[paras.toLowerCase()];  
	if(typeof(returnValue)=="undefined"){  
		return "";  
	}else{  
		return returnValue; 
	}
}




$(window).load(function(){
		var j = o = $('#detail h3'),t = 0,s = false;
		while(o[0].tagName != 'BODY'){
			t+=o[0].offsetTop;
			var o=o.offsetParent();
		}


		$(window).scroll(function(){
			var nu = $(this).scrollTop();
			if(nu > t){j.addClass('abs');j.parent().css('padding-top','81px');s = true;}
			if(s && nu <=t){j.removeClass('abs').addClass('sie');j.parent().removeAttr('style');s = false;}
			
		});

});

$(window).scroll(function() {
	if ($(this).scrollTop() > 800) {
		$("#scrollGoTop").show();
	}else{
		$("#scrollGoTop").hide();
	};
});


$(function(){
	$('body').append('<a id="scrollGoTop" target="_self" href="###" style="display:none;">回顶部</a>');
	$('body').append('<style>#scrollGoTop{position:fixed;_position:absolute;left:50%;margin:0 0 0 509px;width:25px;height:90px;line-height:400px;overflow:hidden;bottom:20px;background:url(http://img1.imglafaso.com/images/scrollGoTop.png) no-repeat;_top:expression(eval(documentElement.scrollTop+documentElement.clientHeight-this.clientHeight-20));}#scrollGoTop:hover{background-position:-25px 0;}</style>')



	$("#scrollGoTop").click(function(){$(window).scrollTop(0)});
});

